package com.yongchun.controller;

import com.yongchun.commons.StringUtil;
import com.yongchun.config.TokenVO;
import com.yongchun.config.adapay.AdapayItemConfig;
import com.yongchun.config.adapay.AdapayUtil;
import com.yongchun.dto.SignatureDTO;
import com.yongchun.model.Player;
import com.yongchun.pubInter.SkJsonResult;
import com.yongchun.service.IPlayerService;
import com.yongchun.vo.SignatureVO;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * @author afeng
 * @version 1.0
 * @date 2023/11/15 下午2:29
 */
@RestController
@RequestMapping("/wechat/")
public class WechatController extends ApiRestController{
    @Autowired
    private IPlayerService playerService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private AdapayUtil adapayUtil;


    @PostMapping("signature")
    public SkJsonResult<SignatureVO> signature(@RequestBody SignatureDTO dto, HttpServletResponse response) {
        if(!dto.getPlayerId().endsWith("@my2019")){
            return SkJsonResult.ok();
        }
        if(dto.getPlayerId().length()!=35){
            return SkJsonResult.ok();
        }
        try {
            Player player = playerService.getDetail(dto.getPlayerId());
            WxJsapiSignature signature = wxMpService.switchoverTo(dto.getAppId()).createJsapiSignature(URLDecoder.decode(dto.getUrl(), "UTF-8"));
            AdapayItemConfig config = adapayUtil.getOneAdapayConfigByAppId(dto.getAppId());
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(dto.getAppId(), config.getWxSecret(), dto.getCode());
            WxOAuth2UserInfo user = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            System.out.println(user.getOpenid());
            TokenVO tokenVO = new TokenVO();
            tokenVO.setOpenId(user.getOpenid());
            tokenVO.setWxAppId(config.getWxAppId());
            setToken(tokenVO, response);
            SignatureVO vo=map(signature, SignatureVO.class);
            if(StringUtil.isNotObjEmpty(player)){
                vo.setPlayerName(player.getName());
            }
            return SkJsonResult.ok(vo);
        } catch (Exception e) {

            e.printStackTrace();
            return SkJsonResult.fail();
        }
    }
}
